package com.d404.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import im.beans.Classify;
import im.beans.User;
import manager.PersistentManager;

/**
 * Servlet implementation class Register
 */
//@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public static final String SUCCESS = "1";
	public static final String USER_EXISTS = "2";
	public static final String FALIED = "3";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		String status = "9";// 未知状态
		
		boolean isuserExist = false;
		
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try{
		// 根据账号查找用户
		Query q = session.createQuery("from User u where u.account = ?");
		q.setParameter(0, userName);

		User tempUser = null;
		// 获取所有结果
		List<User> users = q.list();
		for (User u : users) {
			isuserExist = true;
			tempUser = u;
		}

		// 创建未分组
		Classify classify = new Classify();
		classify.setClassifyName("未分组");

		/**
		 * 若用户存在，则返回用户存在信息 若用户不存在，则保存用户并且保存此用户的第一个分组，即未分组
		 */
		if (isuserExist) {
			status = USER_EXISTS;
		} else {
			// 若用户不存在，创建用户
			User user = new User();
			user.setAccount(userName);
			user.setPassword(password);
			// 存储用户
			session.save(user);
			
			//设置分组表owner用户
			classify.setOwer(user);
			classify.setOwerName(userName);
			classify.setFriendCount(0L);
			
			// 存储分组
			session.save(classify);
		}
		session.getTransaction().commit();
		if (!status.equals(USER_EXISTS)) {
			status = SUCCESS;
		}
		}catch(Exception e)
		{
			tx.rollback();
			status = FALIED;
		} finally
		{
//			session.close();
		}
		
		System.out.println("register:"+status);
		
		response.getWriter().append(status);
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
